<?php

declare(strict_types=1);

namespace app\chat\controller\admin;

use think\Request;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\chat\model\User as ChatUser;
use app\chat\model\ServiceLog;
use app\chat\model\Record;
use think\facade\Db;

class User extends Backend
{
    public function initialize()
    {
        $this->model = new ChatUser;
    }

    /**
     * 会话列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $user = $this->model->sheepFilter()->with(['user', 'customer_service'])->where('auth', 'user')->order('id desc')->paginate((int)request()->param('list_rows', 10));
        return success('获取成功', $user);
    }


    /**·
     * 删除会话
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $id = explode(',', $id);

        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $user) {
                // 删除这个会话的所有服务记录
                ServiceLog::where('chat_user_id', $user->id)->delete();

                // 删除这个会话的所有聊天记录
                Record::where('chat_user_id', $user->id)->delete();
                
                // 删除这个会话
                $user->delete();
            }
        });

        return success('删除成功');
    }
}
